<script lang="ts" setup>
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from "vue";

const targetRef = ref<HTMLElement | null>();
const height = ref(0);
const visible = ref(false);
defineProps<{ message?: string }>();

const contentStyles = computed(() => {
  return {
    top: `-${height.value}px`,
  };
});

function getHeight() {
  nextTick(() => {
    if (targetRef.value) {
      height.value = targetRef.value.getBoundingClientRect().height + 10;
    }
  });
}

onMounted(() => {
  document.addEventListener("click", clickOutsideHandler);
});

const clickOutsideHandler = (e: any) => {
  if (!e.target.closest(".umrp-popconfirm")) {
    visible.value = false;
  }
};

const showContent = () => {
  visible.value = true;
  getHeight();
};

onBeforeUnmount(() => {
  document.removeEventListener("click", clickOutsideHandler);
});
</script>

<template>
  <div class="umrp-popconfirm">
    <div @click="showContent">
      <slot></slot>
    </div>
    <div class="umrp-popconfirm-body" v-show="visible" ref="targetRef" :style="contentStyles">
      <div class="umrp-popconfirm-content">{{ message }}</div>
      <div class="umrp-popconfirm-footer">
        <umrp-space :size="6">
          <umrp-button type="default" size="mini" @click="visible = false">取消</umrp-button>
          <umrp-button type="primary" size="mini" @click="visible = false">确认</umrp-button>
        </umrp-space>
      </div>
      <div class="umrp-popconfirm-arrow"></div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.umrp-popconfirm {
  position: relative;

  &-body {
    min-width: 180px;
    padding: 12px 12px 10px;
    position: absolute;
    background-color: #fff;
    top: 0;
    right: 0;
    border: 1px solid #f2f2f2;
    border-radius: 4px;
    box-shadow: 0 4px 10px #0000001a;
  }

  &-arrow {
    content: "";
    height: 8px;
    width: 8px;
    position: absolute;
    display: block;
    box-sizing: border-box;
    transform: rotate(45deg);
    transform-origin: 50% 50% 0;
    background-color: #fff;
    right: 20px;
    bottom: -5px;
  }

  &-footer {
    margin-top: 6px;
    display: flex;
    justify-content: end;
  }
}
</style>
